package com.cqrt.config;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
public class DownloadResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, 
                           Class<? extends HttpMessageConverter<?>> converterType) {
        // 只处理文件下载相关的控制器方法
        return returnType.getMethod().getName().contains("download");
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, 
                                 MediaType selectedContentType,
                                 Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                 ServerHttpRequest request, 
                                 ServerHttpResponse response) {
        
        HttpServletResponse servletResponse = 
            ((ServletServerHttpResponse) response).getServletResponse();
        
        try {
            // 在响应提交前进行处理
            if (body instanceof Exception) {
                // 处理异常情况
                if (!servletResponse.isCommitted()) {
                    servletResponse.reset();
                    servletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    servletResponse.setContentType("text/plain; charset=UTF-8");
                    servletResponse.getWriter().write("下载失败: " + ((Exception) body).getMessage());
                }
                return null;
            }
        } catch (Exception e) {
            // 记录错误
            System.err.println("处理响应时发生错误: " + e.getMessage());
        }
        
        return body;
    }
}